package com.example.r2022913.controller.WxController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.r2022913.common.ApiRestResponse;
import com.example.r2022913.model.entity.WxEntity.AdminUserMailEntity;
import com.example.r2022913.service.WxService.AdminMailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.poi.ss.usermodel.IconMultiStateFormatting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("wx/wc")
@Api(tags = "wx小程序服务  AdminMailController")
@Slf4j
public class AdminMailController {

    @Autowired
    AdminMailService adminmailService;

    //和微信小程序绑定的appid
    @Value("${appid}")
    private String appid;

    //和微信小程序绑定的secret
    @Value("${secret}")
    private String secret;


//    获取openid
    public Map getOpenidAndSessionKey(String appid, String secret, String code) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();

        log.info("appid是==》{}", appid);
        log.info("secret-->{}", secret);
        log.info("从前端拿到的code是===>{}", code);


        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

        Request request = new Request.Builder().url(url).build();

        Response response = okHttpClient.newCall(request).execute();

        if (response.isSuccessful()) {
            JSONObject jsonResult = JSONObject.parseObject(response.body().string());

            log.info("获取的响应结果体是===》{}", jsonResult);

            String openid = jsonResult.getString("openid");
            String sessionKey = jsonResult.getString("session_key");

            System.out.println("openid:   " + openid);
            System.out.println("sessionKey:   " + sessionKey);
            HashMap<Object, Object> hashmap = new HashMap<>();
            hashmap.put("openid", openid);
            hashmap.put("sessionKey", sessionKey);
            return hashmap;
        }

        return null;

    }


    //增加
    @RequestMapping("/adminMailAdd")
    public int adminMailAdd(AdminUserMailEntity adminUserMailEntity,@RequestParam String code) throws IOException {
        if (adminUserMailEntity == null||code==null) {
            return 0;
        }
        Map map = getOpenidAndSessionKey(appid, secret, code);
        String openid = (String)map.get("openid");
        adminUserMailEntity.setOpenId(openid);
        return adminmailService.adminMailAdd(adminUserMailEntity);
    }

    //自动获取opnId参数
    //查询所有
    @RequestMapping("/adminMailList")
    public ApiRestResponse adminMailList(@RequestParam(defaultValue = "1") Integer pageNum,
                                                   @RequestParam(defaultValue = "10") Integer pageSize,
                                                   @RequestParam(defaultValue = "") Map<String, Object> params,@RequestParam String code) throws IOException {
        if (code==null) {
            return null;
        }
        Map map = getOpenidAndSessionKey(appid, secret, code);
        String openid = (String)map.get("openid");
        IPage page = adminmailService.adminMailList(pageNum,pageSize,params,openid);
        return ApiRestResponse.success(page);
    }


    //指定id查询
    @RequestMapping("/adminMailById")
    public AdminUserMailEntity adminMailById(@RequestParam Long adminId) {

        System.out.println("访问了指定id查询接口");

        if (adminId == null) {
            return null;
        }
        return adminmailService.adminMailById(adminId);
    }

    //查询记录数
    @RequestMapping("/adminMailCount")
    public Integer adminMailCount(@RequestParam String code) throws IOException {
        if (code == null) {
            return 0;
        }
        Map map = getOpenidAndSessionKey(appid, secret, code);
        String openid = (String)map.get("openid");
        return adminmailService.adminMailCount(openid);
    }

}


